package com.dymall.controller;

import com.dymall.common.domain.PageDTO;
import com.dymall.common.domain.PageQuery;
import com.dymall.common.utils.BeanUtils;
import com.dymall.domain.dto.ItemDTO;
import com.dymall.domain.dto.OrderDetailDTO;
import com.dymall.domain.po.Item;
import com.dymall.service.ItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "商品管理相关接口")
@RestController
@RequestMapping("/items")
@RequiredArgsConstructor
public class ItemController {
    private final ItemService itemService;
    private final StringRedisTemplate stringRedisTemplate;

    @ApiOperation("根据id批量查询商品")
    @GetMapping
    public List<ItemDTO> queryItemByIds(@RequestParam("ids") List<Long> ids){
        //如果需要绑定复杂对象（如 List<Item>），通常需要使用 @RequestBody 或 @RequestParam 注解明确指定参数来源。
        return itemService.queryItemByIds(ids);
    }

    @ApiOperation("新增商品")
    @PostMapping
    public void saveItem(@RequestBody ItemDTO itemDTO){
        Item item = BeanUtils.copyBean(itemDTO, Item.class);
        itemService.save(item);
        // 删除redis中的缓存
        stringRedisTemplate.delete("queryByPage");
    }

    @ApiOperation("更新商品")
    @PutMapping
    public void updateItem(@RequestBody ItemDTO itemDTO){
        // 不允许修改商品状态，所以强制设置为null，更新时，就会忽略该字段
        itemDTO.setStatus(null);
        itemService.updateById(BeanUtils.copyBean(itemDTO, Item.class));
        // 删除redis中的缓存
        stringRedisTemplate.delete(List.of("queryByPage","item"));
    }

    @ApiOperation("分页查询商品")
    @GetMapping("/page")
    public PageDTO<ItemDTO> queryItemByPage(PageQuery pageQuery){
        return itemService.queryItemByPage(pageQuery);
    }

    @ApiOperation("更新商品状态")
    @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status){
        Item item = new Item().setId(id).setStatus(status);
        itemService.updateById(item);
        // 删除redis中的缓存
        stringRedisTemplate.delete(List.of("queryByPage","item"));
    }

    @ApiOperation("批量扣减库存")
    @PutMapping("/stock/deduct")
    public void deductStock(@RequestBody List<OrderDetailDTO> items){
        itemService.deductStock(items);
    }

    @ApiOperation("根据id查询商品")
    @GetMapping("/{id}")
    public ItemDTO queryItemById(@PathVariable("id") Long id){
        return itemService.queryItemById(id);
    }

    @ApiOperation("根据id删除商品")
    @DeleteMapping("/{id}")
    public void deleteItemById(@PathVariable("id") Long id){
        itemService.removeById(id);
        // 删除redis中的缓存
        stringRedisTemplate.delete(List.of("queryByPage","item:"+id));
    }
}
